import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

import '../../../lib_basemodel/chat_room/flyScreen/flying_data.dart';
import '../../../lib_runtime/event_center.dart';
import '../../../lib_runtime/event_constant.dart';
import '../../../lib_runtime/global_config.dart';
import '../../float_screen/gift_floating_screen.dart';
import '../../utils/screen_utils.dart';
import 'float_screen_controller.dart';

/// 飘屏
class FloatScreen {
  static OverlayEntry? _entry;
  static StreamSubscription<Event>? _eventSub;

  /// 登录成功之后，init初始化
  static void init() {
    if (_entry != null) {
      dispose();
    }
    _eventSub =
        eventCenter.subscribe(EventConstant.floatScreen).listen((event) {
      if (event.data is FlyingData) {
        if (GlobalConfig.appLifecycleActive) {
          _show(event.data);
        }
      }
    });
  }

  /// 退出登录，或者不需要的时候调用
  static void dispose() {
    _eventSub?.cancel();
    _entry?.remove();
    _entry = null;
    Get.delete<FloatScreenController>(force: true);
  }

  static void _show(FlyingData data) {
    Get.put(FloatScreenController(), permanent: true).push(data);
    if (_entry == null) {
      OverlayState? overlayState = Overlay.of(Get.context!);
      _entry = OverlayEntry(builder: (context) {
        return _FloatScreenWidget();
      });
      overlayState.insert(_entry!);
    }
  }
}

class _FloatScreenWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetBuilder<FloatScreenController>(
      builder: (logic) {
        if (logic.data == null) {
          return const SizedBox.shrink();
        }
        Widget child = _genChile(logic.data!);
        return GetBuilder<FloatScreenController>(
            id: 'trx',
            builder: (logic) {
              return Container(
                width: ScreenUtils.ins.screenWidth,
                height: 70,
                alignment: Alignment.topCenter,
                margin: const EdgeInsets.only(top: 70),
                transform: Matrix4.identity()..translate(logic.trx),
                child: child,
              );
            });
      },
    );
  }

  Widget _genChile(FlyingData data) {
    switch (data.type) {
      case FlyingType.gift:
        return GiftFloatingScreen(data: data);

      default:
        return const SizedBox.shrink();
    }
  }
}
